<?php

namespace stlswm\KhyTms;

use Exception;
use GuzzleHttp\Exception\GuzzleException;

/**
 * Class Client
 *
 * @package stlswm\KhyTms
 */
class Client
{
    const EnvTest = 1;
    const EnvProduction = 2;
    /**
     * @var string 用户名
     */
    protected $userName;

    /**
     * @var string 密码
     */
    protected $password;

    /**
     * @var string 接口令牌
     */
    protected $accessToken;

    /**
     * @var int 环境
     */
    protected $env = self::EnvProduction;

    /**
     * @param string $accessToken
     */
    public function setAccessToken(string $accessToken)
    {
        $this->accessToken = $accessToken;
    }

    public function getUserName(): string
    {
        return $this->userName;
    }

    public function getPassword(): string
    {
        return $this->password;
    }

    public function getAccessToken(): string
    {
        return $this->accessToken;
    }

    /**
     * 切换为测试环境
     */
    public function asTest()
    {
        $this->env = self::EnvTest;
    }

    /**
     * @return string
     */
    public function getApiDomain(): string
    {
        if ($this->env == self::EnvProduction) {
            return 'http://api.56ctms.com';
        }
        return 'http://api.test.56ctms.com';
    }

    /**
     * Json 请求
     *
     * @param string  $router
     * @param Request $request
     *
     * @return string
     * @throws GuzzleException
     * @throws Exception
     */
    public function jsonReq(string $router, Request $request): string
    {
        $client = new \GuzzleHttp\Client([
            'timeout' => 10,
        ]);
        $api = $this->getApiDomain() . $router;
        if ($this->accessToken) {
            if (strpos($api, '?') === FALSE) {
                $api .= '?';
            } else {
                $api .= '&';
            }
            $api .= 'access_token=' . $this->accessToken;
        }
        $response = $client->request("POST", $api, [
            "headers" => [
                "Content-Type" => 'application/json',
            ],
            'body'    => $request->jsonFormat(),
        ]);
        if ($response->getStatusCode() != 200) {
            throw new Exception("网络请求错误：" . $response->getStatusCode());
        }
        return (string)$response->getBody();
    }


    /**
     * @param string $userName
     * @param string $password
     *
     * @return Client
     */
    public static function newClient(string $userName, string $password): Client
    {
        $client = new Client();
        $client->userName = $userName;
        $client->password = $password;
        return $client;
    }
}
